package util

import (
	"errors"
	"net"
	"sieve_admin_server_userpass/lib/util/rand"
	"strconv"
)

func ListenRandom(from, to int) (net.Listener, int, error) {
	return ListenHostRandom("", from, to)
}

func ListenHostRandom(host string, from, to int) (net.Listener, int, error) {
	if from > to {
		from, to = to, from
	}
	r := rand.In(from, to)
	for p := r; p <= to; p++ {
		l, e := net.Listen("tcp", host+":"+strconv.Itoa(p))
		if e == nil {
			return l, p, nil
		}
	}
	for p := r - 1; p >= from; p-- {
		l, e := net.Listen("tcp", host+":"+strconv.Itoa(p))
		if e == nil {
			return l, p, nil
		}
	}
	return nil, 0, errors.New("no valid port")
}
